﻿// For an introduction to the Navigation template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232506
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    var nav = WinJS.Navigation;
    var Background = Windows.ApplicationModel.Background;

    app.addEventListener("activated", function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
                CalenderDB.createDB();

            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }

            Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().clear();
            Windows.UI.Notifications.BadgeUpdateManager.createBadgeUpdaterForApplication().clear();
            schedualTile();
            //updateBadge();
            //RequestLockScreenAccess();

            if (app.sessionState.history) {
                nav.history = app.sessionState.history;
            }
            args.setPromise(WinJS.UI.processAll().then(function () {
                document.getElementById("monthviewbar").addEventListener("click", goToMonthView, false);
                document.getElementById("dayviewbar").addEventListener("click", goToDayView, false);
                //document.getElementById("eventviewbar").addEventListener("click", goToEventView, false);
                //document.getElementById("neweventbar").addEventListener("click", goToNewEvent, false);
                document.getElementById("gototodaybar").addEventListener("click", goToToday, false);

                if (nav.location) {
                    nav.history.current.initialPlaceholder = true;
                    return nav.navigate(nav.location, nav.state);
                } else {
                    return nav.navigate(Application.navigator.home);
                }
            }));
        }
    });

    function schedualTile() {
        createTile()
        var intvalId = window.setInterval("createTile()", 30 * 1000);
    }

    function updateBadge() {
        CalenderDB.readData();
    }

    function RequestLockScreenAccess() {
        var result = Background.BackgroundExecutionManager.getAccessStatus();
        switch (result) {
            case Background.BackgroundAccessStatus.denied:
                //WinJS.log && WinJS.log("This app is not on the lock screen.", "sample", "status");
                break;

            case Background.BackgroundAccessStatus.allowedWithAlwaysOnRealTimeConnectivity:
                //WinJS.log && WinJS.log("This app is on the lock screen and has access to Always-On Real Time Connectivity.", "sample", "status");
                break;

            case Background.BackgroundAccessStatus.allowedMayUseActiveRealTimeConnectivity:
                //WinJS.log && WinJS.log("This app is on the lock screen and has access to Active Real Time Connectivity.", "sample", "status");
                break;

            case Background.BackgroundAccessStatus.unspecified:
                //WinJS.log && WinJS.log("The user has not yet taken any action. This is the default setting and the app is not on the lock screen.", "sample", "status");
                Background.BackgroundExecutionManager.requestAccessAsync().done(function (result) {
                    CalenderDB.readData();

                    switch (result) {
                        case Background.BackgroundAccessStatus.denied:
                            break;
                        case Background.BackgroundAccessStatus.allowedWithAlwaysOnRealTimeConnectivity:
                            break;
                        case Background.BackgroundAccessStatus.allowedMayUseActiveRealTimeConnectivity:
                            break;
                        case Background.BackgroundAccessStatus.unspecified:
                            break;
                    }
                }, function (e) {
                    var m = "error info";
                });
                break;
        }
    }

    function goToMonthView() {
        WinJS.Navigation.navigate("/pages/MonthView/MonthView.html");
        hideAppbar();
    }

    function goToDayView() {
        WinJS.Navigation.navigate("/pages/DayView/DayView.html");
        hideAppbar();
    }

    function goToToday() {
        if (currentView === "month") {
            pushBtm();
        } else {
            currentYear = tY;
            currentMonth = tM;
            currentDay = tD;
            WinJS.Navigation.navigate("/pages/DayView/DayView.html");
        }
        hideAppbar();
    }

    function goToEventView() {
        WinJS.Navigation.navigate("/pages/EventView/EventView.html");
    }

    function goToNewEvent() {
        WinJS.Navigation.navigate("/pages/EventForm/EventForm.html");
    }

    function hideAppbar() {
        document.getElementById("appbar").winControl.hide();
    }

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. If you need to 
        // complete an asynchronous operation before your application is 
        // suspended, call args.setPromise().
        app.sessionState.history = nav.history;
    };

    app.start();
})();

(function () {
    WinJS.Namespace.define("CalendarApp", {
        removeAppBars: function () {
            // Remove AppBar from previous scenario
            var otherAppBars = document.querySelectorAll('div[data-win-control="WinJS.UI.AppBar"]');
            var len = otherAppBars.length;
            for (var i = 0; i < len; i++) {
                var otherScenarioAppBar = otherAppBars[i];
                otherScenarioAppBar.parentNode.removeChild(otherScenarioAppBar);
            }
        }
    });

})();

function createTile() {
    TileWideText01();
}

function TileWideText01() {
    var wideTileContent = NotificationsExtensions.TileContent.TileContentFactory.createTileWideText01();
    var t = new Date();
    var hour = t.getHours();
    var minute = t.getMinutes();
    var year = t.getFullYear();
    var month = t.getMonth();
    var day = t.getDate();
    var dayOfWeek = GetDayOfWeek();
    var chen = shiChen[hour];
    var lunar = new calendar(year, month);
    var nMonth = monthName[(lunar[day - 1].lMonth - 1)];
    var nDay = cDay(lunar[day - 1].lDay);
    var solarFestival = lunar[day - 1].solarFestival;
    var lunarFestival = lunar[day - 1].lunarFestival;
    var solarTerms = lunar[day - 1].solarTerms;
    var holiday = "";

    minute = minute.toString().length === 1 ? ("0" + minute) : minute;
    if (solarFestival !== "") {
        holiday = solarFestival;
    }

    if (lunarFestival !== "") {
        holiday += "  " + lunarFestival;
    }

    if (solarTerms !== "") {
        holiday += "  " + solarTerms;
    }

    var showHour = hour + ":" + minute + "  (" + chen + "时)";
    var showYear = year + "年" + (month + 1) + "月" + day + "日  " + dayOfWeek;
    var showLunar = "农历  " + nMonth + "" + nDay;

    wideTileContent.textHeading.text = showHour
    wideTileContent.textBody1.text = showYear;
    wideTileContent.textBody2.text = showLunar;
    wideTileContent.textBody3.text = holiday;

    //var squareTileContent = NotificationsExtensions.TileContent.TileContentFactory.createTileSquareText03();
    //squareTileContent.textBody1.text = hour + ":" + minute + "" + chen + "时";
    //squareTileContent.textBody2.text = year + "年" + (month + 1) + "月" + day + "日";
    //squareTileContent.textBody3.text = dayOfWeek;
    //squareTileContent.textBody4.text = holdiay;

    var squareTileContent = NotificationsExtensions.TileContent.TileContentFactory.createTileSquareText01();
    squareTileContent.textHeading.text = hour + ":" + minute + "  " + chen + "";
    squareTileContent.textBody1.text = year + "年" + (month + 1) + "月" + day + "日";
    squareTileContent.textBody2.text = dayOfWeek + holiday;
    squareTileContent.textBody3.text = nMonth + "" + nDay;;
    //squareTileContent.textBody3.text = holiday;

    wideTileContent.squareContent = squareTileContent;
    //var futureTile = new Notifications.ScheduledTileNotification(tileContent.getXml(), dueTime);
    //Notifications.TileUpdateManager.createTileUpdaterForApplication().addToSchedule(futureTile);

    Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().update(wideTileContent.createNotification());
}

function TileWideBlockAndText01() {
    var wideTileContent = NotificationsExtensions.TileContent.TileContentFactory.createTileWideBlockAndText01();
    var t = new Date();
    var dayOfWeek = GetDayOfWeek();
    var hourMinute = t.toLocaleTimeString().substring(0, 5);
    wideTileContent.textBlock.text = "13";
    wideTileContent.textSubBlock.text = "子时";

    var squareTileContent = NotificationsExtensions.TileContent.TileContentFactory.createTileSquareText01();
    squareTileContent.textHeading.text = t.toLocaleTimeString();
    squareTileContent.textBody1.text = t.toLocaleDateString();

    wideTileContent.squareContent = squareTileContent;
    //var futureTile = new Notifications.ScheduledTileNotification(tileContent.getXml(), dueTime);
    //Notifications.TileUpdateManager.createTileUpdaterForApplication().addToSchedule(futureTile);

    Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().update(wideTileContent.createNotification());

}